﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Xceed.Silverlight.Compatibility;

namespace Xceed.Silverlight.Utils
{
  internal static class VisualTreeExtensions
  {
    internal static bool IsDescendant( this DependencyObject child, DependencyObject root )
    {
      return root.IsAncestor( child );
    }

    internal static bool IsAncestor( this DependencyObject root, DependencyObject child )
    {
      while( child != null )
      {
        if( child == root )
          return true;

        child = VisualTreeHelper.GetParent( child );
      }

      return false;
    }

    internal static T GetElementOrParent<T>( this DependencyObject element ) where T : DependencyObject
    {
      return ( T )element.GetElementOrParentBase<T>();
    }

    internal static DependencyObject GetElementOrParentBase<T>( this DependencyObject element )
    {
      while( ( element != null ) && !( element is T ) )
      {
        element = VisualTreeHelper.GetParent( element );
      }

      return element;
    }

    internal static IEnumerable<DependencyObject> GetAncestors( this DependencyObject source )
    {
      if( source == null )
        yield break;

      DependencyObject parent = VisualTreeHelper.GetParent( source );

      while( parent != null )
      {
        yield return parent;

        parent = VisualTreeHelper.GetParent( parent );
      }
    }

    internal static bool IsFocusAncestor( this DependencyObject ancestor, DependencyObject focusScope )
    {
      return ancestor.IsAncestor( CompatibilityUtils.GetFocusedElement( focusScope ) as DependencyObject );
    }

    internal static bool EnsureHasFocus( this Control element, DependencyObject scopeLimit )
    {
      DependencyObject focusedElement = CompatibilityUtils.GetFocusedElement( scopeLimit ) as DependencyObject;

      if( scopeLimit == null || scopeLimit.IsAncestor( focusedElement ) )
      {
        if( !element.IsAncestor( focusedElement ) )
        {
          return element.Focus();
        }
        return true;
      }

      return false;
    }
  }
}
